﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TA.DotNetUtils;
using System.ComponentModel;

namespace TA.Turbo.Controls
{
	public class TemplateNode : BaseTreeNode
	{
		#region PUBLIC
		#region INIT
		public TemplateNode()
		{
			this.TemplateId = "";
		}
		#endregion
		#region PROPS
		[NotifyParentProperty(true)]
		[DefaultValue("")]
		public string TemplateId { get; set; }
		[NotifyParentProperty(true)]
		public object Value { get; set; }
		#endregion
		#endregion
		#region INTERNAL
		#region PROPS
		protected override TreeNodeType Type
		{
			get { return TreeNodeType.Template; }
		}
		#endregion
		#region METHODS
		#region RENDER
		protected override void RenderContentsMain(TreeView owner, TreeNodePosition position, int level, System.Web.UI.HtmlTextWriter writer)
		{
			NodeTemplate template = null;
			if (!string.IsNullOrEmpty(this.TemplateId))
			{
				template = owner.GetTemplateById(this.TemplateId);
			}
			else
			{
				List<Tuple<NodeTemplate, int>> weightedTemplates = new List<Tuple<NodeTemplate, int>>();

				foreach (BaseTemplateMapping mapping in owner.TemplateMappings)
				{
					NodeTemplate t = mapping.GetTemplate(owner, level);
					if (t != null)
					{
						weightedTemplates.Add(new Tuple<NodeTemplate, int>(t, mapping.Weight));
					}
				}
				if (weightedTemplates.Count > 0)
				{
					weightedTemplates.Sort((wt1, wt2) => wt2.Item1.CompareTo(wt1.Item1));
					template = weightedTemplates[0].Item0;
				}
			}

			if (template != null)
			{
				if (this.Value != null)
				{
					template.Container.BindDataEntry(this.Value);
				}

				template.Render(writer, owner.GetNextTemplateNodeId());
			}
		}
		#endregion
		#region JSON
		public override void SerializeContents(TA.JSON.JsonWriter jw)
		{
			base.SerializeContents(jw);

			if (!string.IsNullOrEmpty(this.TemplateId))
			{
				jw.PropertyName("T");
				jw.Value(this.TemplateId);
			}
		}
		#endregion
		#endregion
		#endregion

	}
}
